package com.ruoyi.wxorali.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wxorali.constant.WeChatConstant;
import com.ruoyi.wxorali.service.WAVTestService;
import com.ruoyi.wxorali.service.WxServletService;
import com.ruoyi.wxorali.utils.AppUtil;
import com.ruoyi.wxorali.utils.WeChatUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class WxServletServiceImpl implements WxServletService {
	@Resource
	private ISysUserService sysUserService;
	/**
	 *所有来着微信的命令
	 * 备案
	 * 淘宝链接、口令
	 * 查询
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		// xml格式的消息数据
		String respXml = null;
		// 默认返回的文本消息内容
		String respContent = "";
		try {
			// 调用parseXml方法解析请求消息
			Map<String,String> requestMap = WeChatUtil.parseXml(request);
			// 消息类型
			String msgType = (String) requestMap.get(WeChatConstant.MsgType);
			//发送人
			String fromUserName = (String) requestMap.get(WeChatConstant.FromUserName);
			String mes = null;
			// 文本消息
			if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_TEXT)) {
				mes =requestMap.get(WeChatConstant.Content).toString();
				// boolean beian = this.isBeian(fromUserName);//查询是否渠道备案，未备案不允许使用任何功能
				//  if(beian){
				if("查询".equals(mes) ){ //查询
					//带参数返回小程序，其余都交给小程序

				}else if(AppUtil.istbl(mes) ){ //淘宝
				//	respContent = this.gaoyongzhuanlian(fromUserName,mes);
				}else if("更新中间页".equals(mes)){
					//respContent = this.updateMiddlePage(fromUserName);
				}
               /* }else{
                    if("备案更新".equals(mes)){
                        respContent = this.selectBeian(fromUserName);
                    }else{
                        respContent = "您未进行渠道备案，不允许使用任何功能！点击备案，根据提示进行操作！若您已经成功备案，请发送 '备案更新' 命令";
                        String beianurl = this.getBeianUrl(fromUserName);
                        respContent = respContent + "\n \ue22f \ue22f \ue22f \ue22f \ue22f \n"+"<a href='"+beianurl+"'>备案</a>";
                    }
                }*/
				respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
			}
			// 图片消息
			else if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_IMAGE)) {

			}
			// 语音消息
			else if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是语音消息！";
				respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
			}
			// 视频消息
			else if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_VIDEO)) {
				respContent = "您发送的是视频消息！";
				respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
			}
			// 地理位置消息
			else if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！";
				respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
			}
			// 链接消息
			else if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
				respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
			}
			// 事件推送
			else if (msgType.equals(WeChatConstant.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = (String) requestMap.get(WeChatConstant.Event);
				// 关注
				if (eventType.equals(WeChatConstant.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "关注成功";
					//判断此用户存在不存在，不存在则存
					respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
				}
				// 取消关注
				else if (eventType.equals(WeChatConstant.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户不会再收到公众账号发送的消息，因此不需要回复
				}
				// 扫描带参数二维码
				else if (eventType.equals(WeChatConstant.EVENT_TYPE_SCAN)) {
					// TODO 处理扫描带参数二维码事件
				}
				// 上报地理位置
				else if (eventType.equals(WeChatConstant.EVENT_TYPE_LOCATION)) {
					// TODO 处理上报地理位置事件
				}
				// 自定义菜单
				else if (eventType.equals(WeChatConstant.EVENT_TYPE_CLICK)) {
					// TODO 处理菜单点击事件
				}
			}
			mes = mes == null ? "不知道你在干嘛" : mes;
			if(respXml == null){
				respXml = WeChatUtil.sendTextMsg(requestMap, mes);
				System.out.println(respXml);
				return respXml;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";

	};


	@Override
	public String getPhoto(HttpServletRequest request, String Picurl) {
		{ // 对字节数组字符串进行Base64解码并生成图片
			SimpleDateFormat sdfo = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String dateo=sdfo.format(new Date());
			String filename ="/upload/" +dateo + ".jpg";
			String imgFilePath=request.getSession().getServletContext().getRealPath(filename);
			String filepath=request.getSession().getServletContext().getRealPath("/upload");
			File fileo=new File(filepath);
			if(!fileo.exists()){//如果文件夹不存在
				fileo.mkdir();//创建文件夹
			}
			Date date = new Date(System.currentTimeMillis() - 1000 * 60);
			File folder = new File(filepath);
			File[] files = folder.listFiles();
			for (int i=0;i<files.length;i++){
				File file = files[i];
				if (new Date(file.lastModified()).before(date)){
					file.delete();
				}
			}
			URL url = null;
			try {
				url = new URL(Picurl);
				DataInputStream dataInputStream = new DataInputStream(url.openStream());
				File file3=new File(imgFilePath);
				if (!file3.exists()) {
					file3.createNewFile();
				}
				FileOutputStream fileOutputStream = new FileOutputStream(file3);
				ByteArrayOutputStream output = new ByteArrayOutputStream();

				byte[] buffer = new byte[1024];
				int length;

				while ((length = dataInputStream.read(buffer)) > 0) {
					output.write(buffer, 0, length);
				}
				fileOutputStream.write(output.toByteArray());
				dataInputStream.close();
				fileOutputStream.close();

			} catch (MalformedURLException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();

			}
			return filename;

		}
	}


}
